<script setup lang="ts">
import {computed, nextTick, onMounted, ref} from 'vue'
import {settingDB, timerDB} from '@/data/lowdb.ts'
import {Twinkle} from '@/types/twinkle'
import {mergeMultipleSortedArrays} from '@/utils/utils.ts'
import TimeList from '@/views/TimeList.vue'
import {ElMessage} from 'element-plus'

const twinkle = ref<Twinkle>(<Twinkle>{})
// todo 数据更新后，页面上也重新渲染了，但是页面没有拿到最新的数据，从来没遇到过这样的问题
const weatherTimers = computed(() => {
  return twinkle.value.weatherTimers
})
const activeWeather = computed(() => {
  return twinkle.value.activeWeather
})

const allTimes = computed<string[]>(() => {
  const arrays = weatherTimers.value.map((weatherTimer) => {
      return weatherTimer.timers.map(timer => timer.time)
  })
  return mergeMultipleSortedArrays(arrays)
})

onMounted(() => {
    loadDataFromDB()
})

function loadDataFromDB() {
    twinkle.value = timerDB.read().value()
}

// 触发重新加载此组件
const containerActive = ref(true)

function applyWeather(weatherName: string) {
    // 设置激活的天气到数据库
    if (weatherName !== activeWeather.value) {
        timerDB.read()
            .set('activeWeather', weatherName)
            .write()
    }
    loadDataFromDB()
    // 更新页面显示数据
    containerActive.value = false
    nextTick(function () {
        containerActive.value = true
    })
    // 更新twinkle工具的配置
    updateTwinkleSettings(weatherName)
}

const {exec} = require('child_process')

function updateTwinkleSettings(weatherName: string) {
    const msg = ElMessage({
        duration: 0,
        type: 'warning',
        message: '更新中....',
    })
    const adjustmentTimes = weatherTimers.value
        .find(obj => obj.weather === weatherName)
        .timers.map(timer => {
            const newTimer = {...timer}
            newTimer['monitors'] = {}
            return newTimer
        })

    exec('wmic process where (commandline like "%%Twinkle Tray.exe%%" and not name="wmic.exe") delete')
    setTimeout(() => {
        settingDB.read()
            .set('adjustmentTimes', adjustmentTimes)
            .write()
    }, 1200)
    setTimeout(() => {
        exec(`"C:/Program Files (x86)/Stardock/Start11/Launch.exe" /38002AlexanderFrangos.TwinkleTray_m7qx9dzpwqaze!TwinkleTray`)
        msg.close()
        ElMessage({
            type: 'success',
            message: '更新完成！'
        })
    }, 2000)
}
</script>

<template>
  <div class="container" v-if="containerActive">
    <div class="weather" v-for="weatherTimer in weatherTimers" :key="weatherTimer.weather">
      <div class="weatherName noDrag" :class="{active: weatherTimer.weather === activeWeather}"
           @click="applyWeather(weatherTimer.weather)"
      >
        {{ weatherTimer.weather }}
      </div>

      <time-list
          :active="weatherTimer.weather === activeWeather"
          :allTimes="allTimes"
          :timers="weatherTimer.timers"
      />
    </div>
  </div>
</template>

<style scoped lang="stylus">
.container
    width 100%
    display flex
    justify-content space-between

    .weather
        .weatherName
            cursor pointer
            font-size 19px
            font-weight bold
            margin-bottom 10px

        .active
            color blue
</style>
